import { unstable_batchedUpdates } from 'react-dom'
class ReduxHooksStore {
	constructor(reducer, initStore) {
		this.name = '__ReduxHooksStore__'
		this.id = 0
		this.reducer = reducer // 全局的reducer
		this.state = initStore // 全局保存的 state ，每次执行 reducer 会得到新的state
		this.mapConnects = {} // 存放每一个 useConnect 组件的更新函数 用于派发 state 改变带来的更新
	}

	/* 需要对外暴露的接口 */
	exportStore = () => {
		return {
			dispatch: this.dispatch.bind(this),
			subscribe: this.subscribe.bind(this),
			unSubscribe: this.unSubscribe.bind(this),
			getInitState: this.getInitState.bind(this),
		}
	}
	/* 初始化 state */
	getInitState = (mapStoreToState) => {
		// const mapStoreToState = state => ({number:state.number})
		return mapStoreToState(this.state)
	}
	/* 
        更新需要更新的组件
        当 state 改变需要通知每一个使用 useConnect 的组件 ，这个方法就是通知更新
        考虑到  dispatch 的触发场景可以是异步的，unstable_batchedUpdates 开启批量更细原则
     */
	publicRender = () => {
		unstable_batchedUpdates(() => {
			/* 批量更新 */
			Object.keys(this.mapConnects).forEach((name) => {
				const { update } = this.mapConnects[name]
				update(this.state)
			})
		})
	}
	/*  
        更新 state 
        提供给业务组件层，每一个使用 useConnect 的组件通过  dispatch 方法
        改变state 内部原来是通过reducer 产生一个新的 state
    */
	dispatch = (action) => {
		this.state = this.reducer(this.state, action)
		/* 批量更新 */
		this.publicRender()
	}
	/* 注册单个 connect */
	subscribe = (connectCurrent) => {
		const connectName = this.name + ++this.id
		this.mapConnects[connectName] = connectCurrent
		return connectName
	}

	/* 解除绑定 */
	unSubscribe = (connectName) => {
		delete this.mapConnects[connectName]
	}
}
export default ReduxHooksStore
